﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using Microsoft.Expression.Interactivity.Core;

namespace Odyssey.Interactivity
{
    public class BindingEventTrigger : System.Windows.Interactivity.TriggerBase<FrameworkElement>
    {
        public string PropertyName { get; set; }

        public bool TriggerValue { get; set; }

        private object dataContext;


        protected override void OnDetaching()
        {
            base.OnDetaching();
            INotifyPropertyChanged propChanged = dataContext as INotifyPropertyChanged;
            if (propChanged != null)
            {
               
                propChanged.PropertyChanged -= OnPropertyChanged;
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            dataContext = (this.AssociatedObject as FrameworkElement).DataContext;
            INotifyPropertyChanged propChanged = dataContext as INotifyPropertyChanged;
            if (propChanged != null)
            {
                propChanged.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);
            }
        }


        void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == PropertyName)
            {
                var prop = dataContext.GetType().GetProperty(PropertyName);

                if (object.Equals( prop.GetValue(dataContext, null), this.TriggerValue))
                {
                    InvokeActions(dataContext);
                }

            }
        }
    }
}
